package com.xw.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xw.db137.common.JwtUtils;
import com.xw.db137.common.R;
import com.xw.db137.entity.Menu;
import com.xw.db137.entity.User;
import com.xw.db137.service.MenuService;
import com.xw.db137.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @Author: xw
 * @CreateTime: 2024/12/24
 * @Description: 用户
 * @Version: 1.0
 */
@RestController
@CrossOrigin(origins = "*")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    /**
     * 根据登录用户返回用户的菜单集合数据
     * @return
     */
    @GetMapping("/selectusermenu")
    public R selectUserMenu() {
        List<Menu> menus = menuService.selectMenuByUserId(1);
        return new R().addData("menus", menus);
    }
    @GetMapping("/selectById")
    public R selectUserById(@RequestHeader("toke" +
            "n")String token) {
        Integer id = JwtUtils.getJwtToken(token,"userid");
        User userById = userService.getUserById(id);
        return new R().addData("user", userById);
    }
    @GetMapping("/login")
    public R login(String uname , String upwd) {
//        User user = new User();
//        user.setUsername(uname);
//        user.setUserpassword(upwd);
//        QueryWrapper queryWrapper = new QueryWrapper();//构建一个查询容器
//        queryWrapper.setEntity(user);
//        User u = this.userService.getOne(queryWrapper);
        int id = userService.getId(uname,upwd);
        if (id>0){//登录成功
            //生成token
            HashMap<String , Object> map = new HashMap<>();
//            map.put("user", u);
            map.put("userid", id);
            String jwtToken = JwtUtils.createJwtToken(map);
            System.out.println(jwtToken);
            return new R().addData("jwtToken", jwtToken);
        }else {//登录失败
            return new R().setCode(500);
        }

//        return new R().addData("id",id);
    }
    @PostMapping("/insertUser")
    public R insertUser(String name,String pwd) {
        int i = userService.insertUser(name, pwd);
        return new R().addData("i",i);
    }
    @GetMapping("/selectUser")
    public R selectUser() {
        List<User> list = userService.list();
        return new R().addData("list", list);
    }
    @GetMapping("/deleteUser/{id}")
    public R deleteUser(@PathVariable("id") int id) {
        boolean b = userService.removeById(id);
        return new R();
    }
    @PostMapping("/updateUser")
    public R updateUser(@RequestBody User user) {
        boolean update = userService.updateById(user);
        return new R();
    }
}
